<?php

namespace Admin\Controller;
use Admin\Model\AuthGroupModel;
use User\Api\UserApi;
use Wechat\WechatAuth;
/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends CommonController {

    protected $tableName = null;   // 当前数据模型对应表面

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        $key = I('key');
        $value = I('value');
        if($value){
            $map[$key] = array('like','%'.$value.'%');
        }

        $map['m.status'] = array('egt', 0);

        $prefix   = C('DB_PREFIX');
        $model    = M()
            ->table( $prefix.AuthGroupModel::MEMBER.' m' )
            ->join ( $prefix.AuthGroupModel::UCENTER_MEMBER.' um ON um.id=m.uid ', 'LEFT')
            ->join ( $prefix.AuthGroupModel::AUTH_GROUP_ACCESS.' a ON m.uid=a.uid', 'LEFT')
            ->join('left join '.$this->prefix.'business b on m.business_id = b.id', 'LEFT');
        $list = $this->lists($model, $map,'um.id desc','m.uid,m.alias,m.nickname,um.reg_time,m.last_login_time,m.last_login_ip,m.status, um.id, um.pid, um.username, um.mobile, um.email, group_concat(group_id) as group_ids, b.name as business_name', 'uid');

        $this->assign('_list', $list);
        $this->display();
    }
    
    /**
     * 分销散户列表
     */
    public function inviteGeneralList(){
        $inviteList   = $this->getInviteTreeList();
        foreach($inviteList as $key=>$val)
        {
            if(empty($val['business_id'])){     // 获取散户
                $list[] = $val;
            }
        }
        $this->assign('list', $list);
        $this->display('inviteList');
    }

    /**
     * 分销公司列表
     * @author sunbirder
     */
    public function inviteBusinessList(){
        $inviteList   = $this->getInviteTreeList();
        foreach($inviteList as $key=>$val)
        {
            if($val['business_id']){
                $list[] = $val;
            }
        }
        $this->assign('list', $list);
        $this->display('inviteList');
    }


    /**
     * 分销层级说明
    public function inviteExplain(){
        $this->display();
    }
     */


    /**
     * 编辑用户别名
     */
    public function editUserAlias(){
        $uid = I('get.id');

        if (IS_POST) {
            $data = I();
            $memberResult = M('Member')->where(array('uid' => $uid))->save($data);

            # 用户的pid不能是自己
            $user = M('UcenterMember')->where(array('id' => $uid))->find();
            if ($data['pid'] == $uid) {
                $this->error('父级不能是自身!');
            } else {
                $ucenterMemberResult = M('UcenterMember')->where(array('id' => $uid))->save($data);
            }
            $this->success('更新成功!');
        }
        # 用户信息
        $info = M('Member')->where(array('uid'=>$uid))->find();
        # END-用户信息
        # 商家数据列表
        $businessList = M('Business')->where(array('status'=>1))->select();
        # END-商家数据列表
        $this->assign('info', $info);
        $this->assign('businessList', $businessList);

        $userList = $this->getUserTreeToList();
        $this->assign('userList', $userList);

        $this->display();
    }

    /**
     * 获取分销用户树形列表
     */
    private function getInviteTreeList(){
        $map['um.status']  =   array('egt',0);
        $root = IS_ROOT ? 0 : UID;
        $list   = M()
            ->table($this->prefix.'ucenter_member um')
            ->join('left join '.$this->prefix.'member m on m.uid = um.id', 'LEFT')
            ->join('left join '.$this->prefix.'business b on m.business_id = b.id', 'LEFT')
            ->field('um.*, m.business_id, m.alias, b.name as business_name')
            ->where($map)->order('id asc')->select();
        foreach($list as &$arr){
            if($arr['business_id'] && empty($arr['pid'])){
                $arr['tree_name'] = $arr['username'];
                $arr['tree_name'] .= $arr['alias'] ? '（'.$arr['alias'].'）' : '';
                $arr['tree_name'] .= $arr['business_name'] ? "---".$arr['business_name'] : '';
            }else{
                $arr['tree_name'] = $arr['username'];
            }
        }
        $list   = $this->list_to_tree($list, $pk = 'id', $pid = 'pid', 'children', $root);
        return $list;
    }

    /**
     * 分销列表详细
     */
    public function inviteUserDetail(){
        $map['um.status']  =   array('egt',0);
        $map['um.id']  =  I('id');
        $userInfo = M()
            ->table($this->prefix.'ucenter_member um')
            ->join('left join '.$this->prefix.'member m on m.uid = um.id', 'LEFT')
            ->field('um.*, m.business_id, m.alias')
            ->where($map)->find();
        $this->assign('userInfo', $userInfo);
        $this->display();
    }


    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('get.id',0));

        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;

        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        $um['id'] = array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                M('UcenterMember')->where($map)->save(array('status'=>0));
                $this->forbid('Member', $map );
                break;
            case 'resumeuser':
                M('UcenterMember')->where($map)->save(array('status'=>1));
                $this->resume('Member', $map );
                break;
            case 'deleteuser':
                //$this->delete('Member', $map );
                D('Member')->where($map)->delete();
                D('UcenterMember')->where($um)->delete();
                $this->success('删除用户成功！');
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($username = '', $password = '', $repassword = '', $email = '',$mobile='',$group_id=''){
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password, $email,$mobile);
            if(0 < $uid){ //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                $user_role = array('uid' => $uid, 'group_id' => $group_id);
                if(!M('Member')->add($user)){
                    $this->error('用户添加失败！');
                } else {
                    M('auth_group_access')->add($user_role);
                    $this->success('用户添加成功！');
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $rules = M('AuthGroup')->field(true)->where(array('status'=>array('gt',0)))->select();
            $this->assign('rules',$rules);
            $this->display();
        }
    }

    /**
     * 更新用户数据
     */
    public function editUserInfo()
    {
        if(IS_POST){
            $user = I('post.');
            if($user['password'] && $user['repassword'] && $user['password'] != $user['repassword'])
            {
                $this->error('两次输入的密码不一致');
            }
            $Api    =   new UserApi();
            $res    =   $Api->updateInfo($user['id'], $user['password'], $user);
            if($res['status']){
                $result = D('Member')->save($user);
                $this->success('成功修改用户数据！');
            }else
            {
                if(is_numeric($res['info'])){
                    $res['info'] = $this->showRegError($res['info']);
                }
                $this->error($res['info']);
            }

        }else
        {
            $prefix   = C('DB_PREFIX');
            $map['um.id'] = I('get.id');

            $info = M()
                ->table($prefix.'ucenter_member um')
                ->join('left join '.$prefix.'member m on m.uid = um.id')
                ->join('left join '.$prefix.'auth_group_access aga on aga.uid = um.id')
                ->where($map)
                ->field('um.id,um.pid,um.username,um.email,um.mobile,aga.group_id,m.*')
                ->find();
            $this->assign('info',$info);

            $userList = $this->getUserTreeToList();
            $this->assign('userList', $userList);

            $this->display();
        }
    }

    /**
     * 获取用户下拉菜单列表
     * @return array
     */
    private function getUserTreeToList(){
        $map = array();
        $map['um.status']  =   array('egt',0);
        $prefix = C('DB_PREFIX');
        $list   = M()
            ->field('um.id, um.pid, um.username, m.nickname')
            ->table($prefix.'ucenter_member as um')
            ->join ($prefix.'member as m on m.uid=um.id', 'LEFT')
            ->where($map)->order('id asc')->select();

        $root = IS_ROOT ? 0 : UID;
        $userList   = D('Common/Tree')->toFormatTree($list, $title = 'username', $pk = 'id', $pid = 'pid', $root);
        if(IS_ROOT){
            $userList = array_merge(array(0=>array('id'=>0,'username'=>'顶级用户')), $userList);
        }
        return $userList;
    }



    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

    /**
     * 批量删除
     */
    public  function batchDel()
    {
        $id = array_unique((array)I('get.delids',0));

        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        $this->delete('Member', $map );
    }


    /**
     * 行为日志列表
     * @author huajie <banhuajie@163.com>
     */
    public function actionLog()
    {
        //获取列表数据
//        $map = $this->_search();
        $map['al.status'] = array('gt', -1);
        $map['al.user_id'] = I('id');
        $map['al.action_id'] = M('Action')->where(array('name'=>array('in', 'read_category')))->getField('id');
        $prefix = C('DB_PREFIX');
        $model = M()
            ->table($prefix . 'action_log al')
//            ->join($prefix . 'member m ON al.user_id=m.uid', 'LEFT')
//            ->join($prefix . 'document d ON d.id=al.record_id', 'LEFT');
            ->join($prefix . 'category c ON c.id=al.record_id', 'LEFT');
        $list = $this->lists($model, $map, 'al.id desc', 'al.*, c.title');
//        int_to_string($list);
        $this->assign('_list', $list);
        $this->display();
    }

    /**
     * 微信消息推送
     */
    public function wechatPush(){
//        S('WECHATADDONS_CONF', null);
        $this->wechatConfig = S('WECHATADDONS_CONF');
        if(empty($this->wechatConfig)){
            S('WECHATADDONS_CONF',get_addon_config('Wechat'));
            $this->wechatConfig = S('WECHATADDONS_CONF');
        }
        (session('push_user_id') && $uid = session('push_user_id')) || $this->error('用户id不能为空!');
        (I('get.article_id') && $articleId = I('get.article_id')) || $this->error('推荐文章id不能为空!');
        try {
//            $this->wechat = new Wechat($token);
            $this->wechatAuth = new WechatAuth($this->wechatConfig['appid'], $this->wechatConfig['appsecret']);
            $openid = M('MemberAuth')->where(array('uid'=>$uid))->getField('auth_code');
//            $content = M('Document')->where(array('id'=>$articleId))->getField('title'); // 文档描述
            $documentArr = M('Document')->field('id, title, description, cover_id')->where(array('id'=>$articleId))->find(); // 文档描述

            $tokenArr = $this->wechatAuth->getAccessToken();    // 获取access_token

            if($openid && $documentArr){
//                $result = $this->wechatAuth->messageCustomSend($openid, $content);
                $picurl = M('picture')->where(array('id'=>$documentArr['cover_id']))->getField('path');
                $picurl = $picurl ? urlAddDomain($picurl) : '';

                $url = str_replace('admin.php', 'index.php', U('Article/detail', array('id'=>$documentArr['id']), true, true, false));
                /**
                 * 发送一条图文消息
                 * @param  string $openid      用户的openid
                 * @param  string $title       文章标题
                 * @param  string $discription 文章简介
                 * @param  string $url         文章连接
                 * @param  string $picurl      文章缩略图
                 */
                $result = $this->wechatAuth->sendNewsOnce($openid, $documentArr['title'], $documentArr['description'], $url, $picurl);
            }

            if($result['errcode']>0){
                $this->error($this->getWechatError($result['errcode']));
            }else{
                session('push_user_id', null);
                $this->success('推送成功!');
            }
        } catch (\Exception $e) {
            logs('微信认证对象实例化异常!'.$e->getMessage());
            $this->error('微信认证对象实例化异常!'.$e->getMessage());
        }
        $this->error('推送失败!');
    }

    /**
     * 一键微信消息推送
     */
    public function wechatPushAll(){
        $this->wechatConfig = S('WECHATADDONS_CONF');
        if(empty($this->wechatConfig)){
            S('WECHATADDONS_CONF',get_addon_config('Wechat'));
            $this->wechatConfig = S('WECHATADDONS_CONF');
        }
        (I('get.article_id') && $articleId = I('get.article_id')) || $this->error('推荐文章id不能为空!');
        try {
            $this->wechatAuth = new WechatAuth($this->wechatConfig['appid'], $this->wechatConfig['appsecret']);
            $openidList = M('MemberAuth')->getField('auth_code', true);
            $documentArr = M('Document')->field('id, title, description, cover_id')->where(array('id'=>$articleId))->find(); // 文档描述

            if($documentArr){
                $tokenArr = $this->wechatAuth->getAccessToken();    // 获取access_token
                foreach($openidList as $openid){
                    $picurl = M('picture')->where(array('id'=>$documentArr['cover_id']))->getField('path');
                    $picurl = $picurl ? urlAddDomain($picurl) : '';

                    $url = str_replace('admin.php', 'index.php', U('Article/detail', array('id'=>$documentArr['id']), true, true, false));
                    /**
                     * 发送一条图文消息
                     * @param  string $openid      用户的openid
                     * @param  string $title       文章标题
                     * @param  string $discription 文章简介
                     * @param  string $url         文章连接
                     * @param  string $picurl      文章缩略图
                     */
                    $result = $this->wechatAuth->sendNewsOnce($openid, $documentArr['title'], $documentArr['description'], $url, $picurl);
                }
            }

             $this->success('推送成功!');
        } catch (\Exception $e) {
            logs('微信认证对象实例化异常!'.$e->getMessage());
            $this->error('微信认证对象实例化异常!'.$e->getMessage());
        }
        $this->error('推送失败!');
    }


    /**
     * 导出表格文件
     */
    public function outxls()
    {
        session_write_close();      // 此函数会释放session数据的排它锁
        S('excelCount', 0);
        S('excelNumber', 0);
        S('excelStatus', 0);    // 导出状态, 默认未完成  -1没有数据,0未完成, 1已完成
        $where  =   array('um.status'=>array('egt',0));
        $where['al.action_id'] = M('Action')->where(array('name'=>array('in', 'read_category,read_article')))->getField('id', true);
        $where['al.action_id'] && $where['al.action_id'] = array('in', implode($where['al.action_id'], ','));
        if(empty($where['al.action_id']))
            unset($where['al.action_id']);
        $prefix   = C('DB_PREFIX');
        $export_model = M()
                        ->table($prefix.'ucenter_member um')
                        ->join($prefix.'member m ON m.uid=um.id', 'LEFT')
                        ->join($prefix.'action_log al ON al.user_id=um.id', 'LEFT');
        C('LIST_ROWS', -1);    // 不分页配置
//        echo "<pre>";
        $result = $this->lists($export_model, $where, 'um.id desc,al.create_time desc', 'um.*, m.nickname,al.*', null, true);
        S('excelCount', $result['total']);
        $root = IS_ROOT ? 0 : UID;
        $list = D("Common/Tree")->toTree($list=$result['list'], $pk='id',$pid = 'pid',$child = '_child', $root);
        foreach($list as &$arr){
            if($arr['record_id'] && $arr['model']){
                $arr['modelName'] = $arr['model']=='article' ? 'document' : $arr['model'];
                $arr['title'] = M($arr['modelName'])->where(array('id'=>$arr['record_id']))->getField('title');
            }else{
                unset($arr);
            }
        }
        unset($arr);
        $outorder = array();
        foreach($list as $key=>$val)
        {
            S('excelNumber', $key+1);
            $outorder[$key]['no'] = $key+1;
            $outorder[$key]['nickname'] = $val['nickname'];
            $outorder[$key]['mobile'] = $val['mobile'];
            $outorder[$key]['crate_time'] = date('Y-md H:i:s', $val['create_time']);
            $outorder[$key]['remark'] = $val['remark'];
            $outorder[$key]['title'] = $val['title'];
        }
        $headArr=array('序号','用户名', '手机', '操作时间', '行为', '阅读标题');

        $filename='用户阅读记录';
        $this->xlsout($filename,$headArr,$outorder);
    }



    /**
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function list_to_tree($list, $pk = 'id', $ppk = 'pid', $child = '_child', $root = 0, $groupRule = null, $urlRule = null)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                if (is_array($urlRule) && is_string($groupRule) && $urlRule[$data['url']]) {
                    if (in_array($urlRule[$data['url']], explode(',', $groupRule))) {
                        $list[$key]['checked'] = true;
                    }
                    $list[$key]['authId'] = $urlRule[$data['url']] ? $urlRule[$data['url']] : $data[$pk]; // 赋值规则id, 不存在则使用菜单id
                } else {
                    $list[$key]['authId'] = -1; // 规则不存在时. 设置规则id为-1
                    $list[$key]['nocheck'] = true; // $urlRule[$data['url']]规则id不存在情况下, 没有复选框功能
                }
                $refer[$data[$pk]] =& $list[$key]; // 获取当前节点
                // 判断是否存在parent
                $parentId = $data[$ppk];
                if ($refer[$parentId]) { // 计算上级会员数量, 代理数量, 当前层数
                    $refer[$parentId]['member_number']++;
                    $refer[$parentId]['level']++;
                }
            }
//            $listReverse = array_reverse($list); // 倒序

//            foreach ($listReverse as $key => $data) {
//                // 判断是否存在parent
//                $parentId = $data[$ppk];
//                if ($refer[$parentId]) { // 计算上级会员数量, 代理数量, 当前层数
//                    $refer[$parentId]['member_number'] += $data['member_number'];
//                }
//            }

            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$ppk];
                if ($root == $parentId) {
                    $tree[] =& $list[$key]; // $root下的所有节点
                } else {
                    if (isset($refer[$parentId])) {
//                    $parent =& $refer[$parentId];
//                    $parent[$child][$data[$pk]] =& $list[$key];
                        $refer[$parentId][$child][] =& $list[$key]; // 获取父级节点的孩子节点
                    }
                }
            }

        }
        return $tree;
    }

}